#include "view.h"
#include "ui_view.h"
#include "QDebug"
#include <QPainter>
#include <QMessageBox>
#include <QFileDialog>
#include <QStyle>
#include <QStyleOption>
#include <QScreen>

View::View(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::View)
{
    ui->setupUi(this);
    zoomValue = 1.0;
    connect(&timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
}

View::~View()
{
    delete ui;
}

void View::paintEvent(QPaintEvent *)
{
    if (index >= fileList.length()) {
        return;
    }

    QPixmap dest = QPixmap::fromImage(image.scaled(ui->label->size() * zoomValue, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    ui->label->setPixmap(dest);
}

void View::wheelEvent(QWheelEvent *event)
{
    int value = event->delta();
    if (value > 0) {
        if (zoomValue < 1) {
            zoomValue += 0.05;
        }
    } else if (zoomValue > 0.2) {
        zoomValue -= 0.05;
    }
}

void View::mouseMoveEvent(QMouseEvent *event)
{
    if (!isPress) {
        return;
    }

    setCursor(Qt::SizeAllCursor);
    QPoint pos = event->pos();
    interval = pos - this->pos;
    this->pos = pos;
    update();
}

void View::mousePressEvent(QMouseEvent *event)
{
    pos = event->pos();
    isPress = true;
}

void View::mouseReleaseEvent(QMouseEvent *)
{

    isPress = false;
}

// 左旋
void View::on_leftRotate_clicked()
{
    QMatrix matrix;
    matrix.rotate(-90);
    image = image.transformed(matrix);
}

// 右旋
void View::on_rightRotate_clicked()
{
    QMatrix matrix;
    matrix.rotate(90);
    image = image.transformed(matrix);
}

// 选择下一张图片
void View::on_next_clicked()
{
    if (index > fileList.length() - 2) {
        index = 0;
    } else {
        index++;
    }
    image = QImage(fileList[index]);
}

// 选择上一张图片
void View::on_previous_clicked()
{
    if (index < 1) {
        index = fileList.length() - 1;
    } else {
        index--;
    }
    image = QImage(fileList[index]);
}

// 选择图片目录
void View::on_selectDirectory_clicked()
{
    auto path = QFileDialog::getExistingDirectory(this, "请选择图片所在目录");
    QDir dir(path);
    auto imgList = dir.entryList(QStringList()<<"*.png" << "*.bmp" << "*.jpg" << "*.tif" << "*.gif");

    if (imgList.length() == 0) {
        return;
    }

    for (auto file : imgList) {
        fileList.append(path + "/" + file);
    }

    index = 0;
    image = QImage(fileList[index]);
    image.scaled(ui->label->size(), Qt::KeepAspectRatio);
}

// 播放/停止 幻灯片
void View::on_slideBtn_clicked()
{
    if (timer.isActive()) {
        timer.stop();

        ui->slideBtn->setText("播放幻灯片");
    } else {
        timer.start(2000);

        ui  ->slideBtn->setText("停止幻灯片");
    }
}

// 展示图片
void View::onTimeout()
{
    this->on_next_clicked();
}
